package com.jzr.open.db1.service.Impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzr.open.common.SecurityHelper;
import com.jzr.open.db1.mapper.TDeptMapper;
import com.jzr.open.db1.model.TDept;
import com.jzr.open.db1.service.DeptService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl  extends ServiceImpl<TDeptMapper,TDept> implements DeptService {
    public List<Integer> getIdList(Wrapper wrapper) {
        return baseMapper.getIdList(wrapper);
    }

    public Integer getId(Wrapper wrapper) {
        List<Integer> list = getIdList(wrapper);
        return list == null || list.size() <= 0 ? null : list.get(0);
    }

    @Override
    public int save(List<TDept> list) {
        if(list == null || list.isEmpty()){
            return 0;
        }
        Integer userId = SecurityHelper.getUserId();
        int count = 0;
        for(TDept record : list){
            QueryWrapper<TDept> qw = new QueryWrapper<>();
            qw.eq(TDept.Code_,record.getCode());

            if(record.getIsDel() != null && record.getIsDel().booleanValue() == true){
                count += baseMapper.delete(qw);
                continue;
            }
            record.setUpdateBy(userId);
            record.setUpdateTime(LocalDateTime.now());
            Integer id = getId(qw);
            if(id == null){
                count += baseMapper.insert(record);
            }else{
                record.setId(id);
                count += baseMapper.updateById(record);
            }
        }
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(List<TDept> list) {
        if(list == null || list.isEmpty()){
            return 0;
        }
        int count = 0;
        for(TDept record : list){
            QueryWrapper<TDept> qw = new QueryWrapper<>();
            qw.eq(TDept.Code_,record.getCode());
            count += baseMapper.delete(qw);
        }
        return count;
    }
}
